#!/usr/bin/env python
# encoding: utf-8
"""
@author:shucheng
@file:log_util.py
@time:2024/2/20 21:45
@desc 日志工具类
"""
import logging
import os
from datetime import date
from util import file_tool


def get_logger(log_file_name=None, log_file_dir=''):
    """
    获取logger
    参考链接：https://blog.csdn.net/liaotianyin/article/details/130401858
    https://blog.51cto.com/u_14224/7640954
    :return:
    """
    # 确保日志目录存在
    file_tool.ensure_dir_exists(log_file_dir)

    _logger = logging.getLogger()
    _logger.setLevel(logging.INFO)

    # 设置将日志输出到文件中，并且定义文件内容
    # filename = f'D:\\XXX\\{str(date.today())}.log'
    # filename = f'{str(date.today())}.log'

    if log_file_name is None:
        log_file_name = str(date.today())
    filename = os.path.join(log_file_dir, log_file_name) + '.log'
    fileinfo = logging.FileHandler(filename, encoding='utf-8')
    fileinfo.setLevel(logging.INFO)

    # 设置将日志输出到控制台
    control_show = logging.StreamHandler()
    control_show.setLevel(logging.INFO)

    # 设置日志的格式
    formatter = logging.Formatter(
        '%(asctime)s - %(filename)s[line:%(lineno)d] - %(threadName)s - %(levelname)s: %(message)s')
    fileinfo.setFormatter(formatter)
    control_show.setFormatter(formatter)

    _logger.addHandler(fileinfo)
    _logger.addHandler(control_show)

    # _logger.info(f"current datetime {datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')}")
    # _logger.warning(f"current datetime {datetime.strftime(datetime.now(), '%Y/%m/%d %H:%M:%S')}")
    return _logger

